package com.zbkj.service.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.custom.Custom;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.product.Product;
import com.zbkj.common.model.product.ProductAttr;
import com.zbkj.common.model.product.ProductAttrValue;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.CustomPreorderRequest;
import com.zbkj.common.request.CustomUpdateRequest;
import com.zbkj.common.request.PreOrderRequest;
import com.zbkj.common.request.ProductFrontSearchRequest;
import com.zbkj.common.response.*;
import com.zbkj.common.vo.MyRecord;
import com.zbkj.service.dao.CustomDao;
import com.zbkj.service.service.*;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CustomServiceImpl extends ServiceImpl<CustomDao, Custom> implements CustomService {

    @Resource
    CustomDao dao;

    @Autowired
    UserService userService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    OrderService orderService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    ProductService productService;


    @Override
    public List<CustomListResponse> getlist() {
//        Integer userId = userService.getUserId();
        Integer userId = 2;
        LambdaQueryWrapper<Custom> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Custom::getPrdId, userId)
                .or()
                .eq(Custom::getRecId, userId);
        List<Custom> list = dao.selectList(lqw);
        List<CustomListResponse> responses = list.stream().map(
                e->{
                    CustomListResponse response = new CustomListResponse();
                    Product product = productService.getById(e.getProductId());
                    BeanUtils.copyProperties(e,response);
                    response.setImgUrl(product.getImage());
                    return response;
                }
        ).collect(Collectors.toList());
        return responses;
    }

    @Override
    public String join(Integer id) {
        Custom custom = dao.selectById(id);
        Integer userid = userService.getUserId();
        if(userid!=null&& !userid.equals(custom.getPrdId())){
            custom.setRecId(userid);
            custom.setStatus(0);
            dao.updateById(custom);
        }else {
            throw new CrmebException("无法获取用户信息");
        }
        return "成功加入该定制";
    }

    @Override
    public String updateStatue(CustomUpdateRequest request) {
        Custom custom = dao.selectById(request.getCustomId());
        if(custom.getStatus()==0){
            custom.setStatus(1);
            custom.setPreOrderId(request.getOrderNo());

        }else if(custom.getStatus()==3){
            custom.setStatus(4);
            custom.setPreOrderId(request.getOrderNo());
        }else {
            throw new CrmebException("定制流程状态出错");
        }
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getOrderNo,request.getOrderNo());
        Order order =orderService.getOne(lqw);
        order.setCancelStatus(6);
        Boolean excut =  transactionTemplate.execute(e -> {
            try {
                dao.updateById(custom);
                orderService.updateById(order);
                return Boolean.TRUE;
            }catch (Exception exception){
                return Boolean.FALSE;
            }

        });
        if(!excut)
            throw new CrmebException("更新流程出错");
        return null;
    }

    @Override
    public CustomIndexResponse index(Integer id) {
        Custom custom = dao.selectById(id);
        if(ObjectUtil.isNull(custom))
            throw new CrmebException("找不到该定制");
        if(!custom.getIsShow() || custom.getIsDel())
            throw new CrmebException("该定制已无法找到");


        CustomIndexResponse response = new CustomIndexResponse();
        BeanUtils.copyProperties(custom,response);
        User user;
        Integer userId = userService.getUserId();
        if(custom.getRecId()==null){
            user = userService.getById(custom.getPrdId());
            response.setRole(0);
        }else {
            if (userId == custom.getRecId()) {//用户是接收方，加载提供方数据
                user = userService.getById(custom.getPrdId());
                response.setRole(0);
            } else if (userId == custom.getPrdId()) {//用户是提供方，加载接收方数据
                user = userService.getById(custom.getRecId());
                response.setRole(1);
            } else {
                throw new CrmebException("用户不是该定制参与者");
            }
        }
        CustomUserInfo info = new CustomUserInfo();
        info.setId(user.getId());
        info.setName(user.getNickname());
        info.setAvatar(user.getAvatar());



        response.setUserInfo(info);
        return response;
    }

    @Override
    public PreOrderRequest preOrder(PreOrderRequest request) {
        LambdaQueryWrapper<ProductAttrValue> lqw = new LambdaQueryWrapper<>();
        request.getOrderDetails().forEach(e->{
            lqw.eq(ProductAttrValue::getProductId,e.getProductId());
            ProductAttrValue productAttr = productAttrValueService.getOne(lqw);
            e.setAttrValueId(productAttr.getId());
        });
//        lqw.eq(ProductAttr::getProductId,request.getOrderDetails().get(0).getProductId());


        return request;
    }
}
